package com.victualler.core.gen.service.impl;

import com.victualler.core.gen.domain.EntityInfoDto;
import com.victualler.core.gen.entity.EntityClassDao;
import com.victualler.core.gen.entity.EntityFieldDao;
import com.victualler.core.gen.repository.EntityClassRepository;
import com.victualler.core.gen.repository.EntityFieldRepository;
import com.victualler.core.gen.service.EntityInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @Aouthor Guoshichang
 * @Date 10:07 on 2018/6/25.
 * @Function
 */
@Service
public class EntityInfoServiceImpl implements EntityInfoService {

    @Autowired
    EntityClassRepository entityClassRepository;
    @Autowired
    EntityFieldRepository entityFieldRepository;

    /**
     * @author Guoshichang
     * @date 10:15 on 2018/6/25.
     * @param className
     * @function 根据entityName获取对应的配置信息
     */
    @Override
    public EntityInfoDto getEntityInfoByClassName(String className) {
        EntityClassDao entityClassDao = entityClassRepository.findByClassName(className).get(0);
        List<EntityFieldDao> entityFieldList = entityFieldRepository.findByParentId(entityClassDao.getId());
        return new EntityInfoDto(entityClassDao,entityFieldList);
    }


    /**
     * @author Guoshichang
     * @date 10:15 on 2018/6/25.
     * @param entityInfoDto
     * @function 保存entityInfo对象
     */
    @Transactional
    @Override
    public void saveEntityInfo(EntityInfoDto entityInfoDto) {
        entityClassRepository.save(entityInfoDto.getEntityClassDao());
        entityInfoDto.getEntityFieldDaoList().forEach(item->{
            item.setParentId(entityInfoDto.getEntityClassDao().getId());
        });
        entityFieldRepository.save(entityInfoDto.getEntityFieldDaoList());
    }
}
